<template>
  <h2>添加客户信息</h2>
  <div class="form-center">

    <el-form :model="form" label-width="auto" style="min-width: 400px">
      <el-form-item label="客户名称">
        <el-input v-model="form.custName"/>
      </el-form-item>
      <el-form-item label="客户地址">
        <el-input v-model="form.address" type="textarea"/>
      </el-form-item>
      <el-form-item label="客户联系方式">
        <el-input v-model="form.phone"/>
      </el-form-item>
      <el-form-item label="客户职业">
        <el-select v-model="form.custType" placeholder="请选择客户的职业">
          <el-option label="金融" value="金融"/>
          <el-option label="教育" value="教育"/>
          <el-option label="建筑" value="建筑"/>
          <el-option label="餐饮" value="餐饮"/>
          <el-option label="旅游" value="旅游"/>
          <el-option label="环保" value="环保"/>
        </el-select>
      </el-form-item>
      <el-form-item label="客户等级">
        <el-select v-model="form.grade" placeholder="请选择客户的等级">
          <el-option label="1" :value="1"/>
          <el-option label="2" :value="2"/>
          <el-option label="3" :value="3"/>
          <el-option label="4" :value="4"/>
        </el-select>
      </el-form-item>
      <div class="btn-center">
        <el-button type="primary" @click="onSubmit">添加</el-button>
        <el-button @click="onCancel">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import {reactive} from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";


// do not use same name with ref
const form = reactive({
  custName: null,
  address: null,
  phone: null,
  custType: null,
  grade: null,
})

const onSubmit = () => {
  console.log('submit!')
  console.log("form:", form)
  axios.post("http://localhost:52010/customer", form).then((response) => {
    const res = response.data
    if (res.code === 200) {
      ElMessage({
        message: '添加成功！',
        type: 'success'
      })
    } else {
      ElMessage.error(res.message || '添加失败！')
    }
  }).catch((error) => {
    // 处理网络异常、服务器异常等
    // 尝试获取后端返回的 message
    const msg = error.response?.data?.message || error.message || '请求异常'
    ElMessage.error(msg)
  });
}

const onCancel = () => {
  console.log('cancel!')
  form.custName = ''
  form.address = ''
  form.phone = ''
  form.custType = []
  form.grade = null
}
</script>

<style scoped>
.form-center {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中（可选）*/
  min-height: 60vh; /* 可选，让它在页面有一定垂直居中感 */
}

.btn-center {
  justify-content: center;
}
</style>